package com.david.mydemo.ctl_storage.controller;

import com.david.mydemo.ctl_storage.service.IStorageService;
import com.david.mydemo.util.MyResponse;
import eu.medsea.mimeutil.MimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Collection;


@RestController
@RequestMapping("/file")
@Slf4j
@Api(value = "文件管理", tags = "文件管理")
public class UploadController {

    @Autowired
    private IStorageService storageService;

    @Value("${storage.local.address}")
    private String url;
    @Value("${storage.local.storagePath}")
    private String path;

    /**
     * 上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传", notes = "上传")
    public MyResponse upload(@RequestParam("file") MultipartFile file) {
        return storageService.store(file, file.getSize(), file.getContentType(), file.getOriginalFilename());
    }

    /**
     * 访问存储对象
     *
     * @param key 存储对象key
     * @return
     */
    @SneakyThrows
    @GetMapping("/fetch/{key:.+}")
    @ApiOperation(value = "访问存储对象", notes = "访问存储对象")
    public ResponseEntity<Resource> fetch(@PathVariable String key) {
        if (key == null) {
            return ResponseEntity.notFound().build();
        }
        if (key.contains("../")) {
            return ResponseEntity.badRequest().build();
        }
        Resource file = storageService.loadAsResource(key);
        MimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
        Collection<?> mimeTypes = MimeUtil.getMimeTypes(file.getURL());
        MediaType mediaType = MediaType.parseMediaType(mimeTypes.toString());
        if (file == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok().contentType(mediaType).body(file);
    }

}
